from PyQt4 import QtCore
import pyqtgraph as pg
import pyqtgraph.parametertree.parameterTypes as pTypes
from pyqtgraph.parametertree import Parameter, ParameterTree, ParameterItem, registerParameterType
import cPickle as pickle

class KConfig(QtCore.QObject):
	
	paraobjdict=None # the dictionary to hold all configurations
	pagelist=['Database Settings','Chart Settings','Report Settings']
	
	def __init__(self, parent=None):
		QtCore.QObject.__init__(self,parent)
	
	@staticmethod
	# convinent class for getting database property
	def GetDatabaseSetting(propertypath):
		return KConfig.__GetSettingValue('Database Settings',propertypath)
	
	@staticmethod
	def __GetSettingValue(pagename,propertypath):
		objdict=KConfig.GetSettings()
		paraobj=objdict[pagename]
		return KConfig.__GetChildSettingObject(paraobj,propertypath)		
				

	@staticmethod
	def __GetChildSettingObject(parentobj,childpathname):
		curlevelchild=''
		remainpath=''
		if childpathname.count('/')<1:
			(curlevelchild,temp,remainpath)=childpathname.partition('/')	
		else:
			(curlevelchild,temp,remainpath)=childpathname.partition('/')			
		for each_child in parentobj.children():
			if each_child.name()==curlevelchild:
				if not remainpath:
					return each_child.value()
				else:
					return KConfig.__GetChildSettingObject(each_child,remainpath)
				
			
	@staticmethod	
	def CreateSettings():
		# create all settings
		paraobjdict={}
	
		# create setting of each page
		for each_page in KConfig.pagelist:
			paraobjdict[each_page]=KConfig.__CreateSettingParameter(each_page)


		# save to file
		KConfig.SaveSettings(paraobjdict)
		
		# return 'state' dictionary
		return paraobjdict
	
	@staticmethod		
	def SaveSettings(paraobjdict):
		
		parastatedict={}
		# convert objet to serializble state
		for each_page in KConfig.pagelist:
			parastatedict[each_page]=paraobjdict[each_page].saveState()
		
		# save to file
		fileobj=open('KSetting.txt','wb')
		pickle.dump(parastatedict,fileobj)
		fileobj.close()
		
	@staticmethod			
	def GetSettings(Refresh=False):		
		# load setting from file, only load from config the first time calling it (unless Refresh is true)
		
		if not KConfig.paraobjdict or Refresh==True:
			fileobj=open('KSetting.txt','rb')
			parastatedict=pickle.load(fileobj)
			fileobj.close()	
			KConfig.paraobjdict={}
			# convert objet to serializble state
			for each_page in KConfig.pagelist:
				newparaobj= Parameter.create(name='params')	
				newparaobj.restoreState(parastatedict[each_page])				
				KConfig.paraobjdict[each_page]=newparaobj	
		# return 'object' dictionary
		return KConfig.paraobjdict
	
	@staticmethod			
	def __CreateSettingParameter(settingname):
		# create database setting
		if settingname=='Database Settings':
			params = [
				{'name': 'Import Historical Daily Data', 'type': 'group', 'children': [
				    {'name': 'EOD Data', 'type': 'group', 'children': [
				        {'name': 'Import Path', 'type': 'str', 'value': r'D:\Dropbox\Trading2013\Data\Daily\EOD'},
				    ]},
				    {'name': 'Stooq Data', 'type': 'group', 'children': [
				        {'name': 'Import Path', 'type': 'str', 'value': r'D:\Dropbox\Trading2013\Data\Daily\stooq_us'},
				    ]},
				]},

			]
		elif settingname=='Chart Settings':
			params = [
				{'name': 'Chart Setting Info', 'type': 'str', 'val': 'empty now'}
			]
		elif settingname=='Report Settings':
			params = [
				{'name': 'Report Setting Info', 'type': 'str', 'val': 'empty now'}
			]
		## Create tree of Parameter objects
		p = Parameter.create(name='params', type='group', children=params)			
		#p.sigTreeStateChanged.connect(self.change)
		return p
	
